package com.ruoyi.system.service.impl;

import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.domain.TechNode;
import com.ruoyi.system.domain.TreeResult;
import com.ruoyi.system.utils.DynamicSorter;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.StandardDb15WMapper;
import com.ruoyi.system.domain.StandardDb15W;
import com.ruoyi.system.service.IStandardDb15WService;

import javax.management.openmbean.TabularType;

/**
 * standardStructService业务层处理
 * 
 * @author ruoyi
 * @date 2025-05-27
 */
@Service
@Slf4j
public class StandardDb15WServiceImpl implements IStandardDb15WService 
{
    @Autowired
    private StandardDb15WMapper standardDb15WMapper;

    /**
     * 查询standardStruct
     * 
     * @param id standardStruct主键
     * @return standardStruct
     */
    @Override
    public StandardDb15W selectStandardDb15WById(String id)
    {
        return standardDb15WMapper.selectStandardDb15WById(id);
    }

    @Override
    public List<StandardDb15W> selectStandardDb15WByBId(String id) {
        return standardDb15WMapper.selectStandardDb15WByBId(id);
    }

    @Override
    public AjaxResult selectStandardDb15WByBIdTree(String id) {
        id = id.replace("-","");
        List<StandardDb15W> standardDb15WList = standardDb15WMapper.selectStandardDb15WByBIdTree(id);
        List<TreeResult> result = new ArrayList<>();

        List<TreeResult> resultTemp = new ArrayList<>();
        for(StandardDb15W standardDb15W: standardDb15WList){
            TreeResult treeResult = new TreeResult();
            treeResult.setContent(standardDb15W.getTechPtbody());
            treeResult.setOrderd(standardDb15W.getTechItid());
            treeResult.setLevel(standardDb15W.getTechLevel());
            treeResult.setTitle(standardDb15W.getTechItid() + "、" + standardDb15W.getTechItname());
            resultTemp.add(treeResult);
        }



        List<TreeResult> filteredListFirst = resultTemp.stream()
                .filter(item -> item.getLevel().equals("1"))
                .collect(Collectors.toList());

        List<TreeResult> filteredListSecond = resultTemp.stream()
                .filter(item -> item.getLevel().equals("2"))
                .collect(Collectors.toList());

        List<TreeResult> filteredListThird = resultTemp.stream()
                .filter(item -> item.getLevel().equals("3"))
                .collect(Collectors.toList());

        List<TreeResult> filteredListFour = resultTemp.stream()
                .filter(item -> item.getLevel().equals("4"))
                .collect(Collectors.toList());

        for(TreeResult standardDb15W: filteredListFirst){
            //一级
            List<TreeResult> resultSecondList = new ArrayList<>();

            for(TreeResult standardSecond : filteredListSecond){

                List<TreeResult> resultThirdList = new ArrayList<>();
                int lastDotIndex = standardSecond.getOrderd().lastIndexOf('.');
                if (lastDotIndex != -1) {
                    String beforeLastDot = standardSecond.getOrderd().substring(0, lastDotIndex);

                    if(standardDb15W.getOrderd().equals(beforeLastDot)){
                        //一级相等
                        resultSecondList.add(standardSecond);

                        for(TreeResult standardThird : filteredListThird){
                            List<TreeResult> resultFourList = new ArrayList<>();

                            int lastDotIndexThird = standardThird.getOrderd().lastIndexOf('.');
                            if (lastDotIndexThird != -1) {
                                String beforeLastDotThird = standardThird.getOrderd().substring(0, lastDotIndexThird);
                                if(standardSecond.getOrderd().equals(beforeLastDotThird)){

                                    resultThirdList.add(standardThird);

                                    for(TreeResult standardFour : filteredListFour){
                                        int lastDotIndexFour = standardFour.getOrderd().lastIndexOf('.');
                                        if (lastDotIndexFour != -1) {
                                            String beforeLastDotFour = standardFour.getOrderd().substring(0, lastDotIndexThird);
                                            if(standardThird.getOrderd().equals(beforeLastDotFour)){
                                                resultFourList.add(standardFour);
                                            }
                                        }
                                    }
                                }
                            }
//                            resultFourList = DynamicSorter.sortByField(resultFourList,"orderd",true);
                            resultFourList = DynamicSorter.sortBySection(
                                    resultFourList,
                                    TreeResult::getOrderd);
                            standardThird.setChildren(resultFourList);

                        }
                    }
                }
//                resultThirdList = DynamicSorter.sortByField(resultThirdList,"orderd",true);
                //                            resultFourList = DynamicSorter.sortByField(resultFourList,"orderd",true);
                resultThirdList = DynamicSorter.sortBySection(
                        resultThirdList,
                        TreeResult::getOrderd);
                standardSecond.setChildren(resultThirdList);
            }
//            resultSecondList = DynamicSorter.sortByField(resultSecondList,"orderd",true);
            //                            resultFourList = DynamicSorter.sortByField(resultFourList,"orderd",true);
            resultSecondList = DynamicSorter.sortBySection(
                    resultSecondList,
                    TreeResult::getOrderd);

            standardDb15W.setChildren(resultSecondList);
            result.add(standardDb15W);
        }
//        result = DynamicSorter.sortByField(result,"orderd",true);
        result = DynamicSorter.sortBySection(
                result,
                TreeResult::getOrderd);
        return AjaxResult.success(result);
    }





    // 构建树形结构
    public static List<TechNode> buildTree(List<TechNode> nodes) {
        Map<String, TechNode> nodeMap = new HashMap<>();
        List<TechNode> rootNodes = new ArrayList<>();

        // 第一次遍历：将所有节点放入Map中
        for (TechNode node : nodes) {
            nodeMap.put(node.getTechItid(), node);
        }

        // 第二次遍历：构建父子关系
        for (TechNode node : nodes) {
            String parentId = node.getTechPtbody(); // 假设techPtbody存储父节点ID

            // 如果父节点ID为空或不存在，则视为根节点
            if (parentId == null || parentId.isEmpty() || !nodeMap.containsKey(parentId)) {
                rootNodes.add(node);
            } else {
                // 找到父节点并添加当前节点为子节点
                TechNode parent = nodeMap.get(parentId);
                parent.addChild(node);
            }
        }

        return rootNodes;
    }









    /**
     * 查询standardStruct列表
     * 
     * @param standardDb15W standardStruct
     * @return standardStruct
     */
    @Override
    public List<StandardDb15W> selectStandardDb15WList(StandardDb15W standardDb15W)
    {
        standardDb15W.setbId(standardDb15W.getbId().replace("-",""));
        return standardDb15WMapper.selectStandardDb15WList(standardDb15W);
    }

    /**
     * 新增standardStruct
     * 
     * @param standardDb15W standardStruct
     * @return 结果
     */
    @Override
    public int insertStandardDb15W(StandardDb15W standardDb15W)
    {
        return standardDb15WMapper.insertStandardDb15W(standardDb15W);
    }

    /**
     * 修改standardStruct
     * 
     * @param standardDb15W standardStruct
     * @return 结果
     */
    @Override
    public int updateStandardDb15W(StandardDb15W standardDb15W)
    {
        return standardDb15WMapper.updateStandardDb15W(standardDb15W);
    }

    /**
     * 批量删除standardStruct
     * 
     * @param ids 需要删除的standardStruct主键
     * @return 结果
     */
    @Override
    public int deleteStandardDb15WByIds(String[] ids)
    {
        return standardDb15WMapper.deleteStandardDb15WByIds(ids);
    }

    /**
     * 删除standardStruct信息
     * 
     * @param id standardStruct主键
     * @return 结果
     */
    @Override
    public int deleteStandardDb15WById(String id)
    {
        return standardDb15WMapper.deleteStandardDb15WById(id);
    }

    @Override
    public int deleteStandardDb15WByBId(String id) {
        return standardDb15WMapper.deleteStandardDb15WByBId(id);
    }
}
